"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from django import forms
import json

from siriuso.forms.widgets import LingvoInputWidget
from .models import *
from siriuso.utils.admin_mixins import TekstoMixin


# Участники чатов
class MesagxiloPartoprenantoInline(admin.TabularInline):
    model = MesagxiloPartoprenanto
    fk_name = 'babilejo'
    extra = 1


# Сообщения чатов
class MesagxiloMesagxoInline(admin.TabularInline):
    model = MesagxiloMesagxo
    fk_name = 'babilejo'
    extra = 1


# Форма для многоязычных чатов
class MesagxiloBabilejoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)

    class Meta:
        model = MesagxiloBabilejo
        fields = [field.name for field in MesagxiloBabilejo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Чаты
@admin.register(MesagxiloBabilejo)
class MesagxiloBabilejoAdmin(admin.ModelAdmin, TekstoMixin):
    form = MesagxiloBabilejoFormo
    list_display = ('id', 'nomo_teksto', 'uuid')
    exclude = ('uuid',)
    inlines = (MesagxiloPartoprenantoInline, )

    class Meta:
        model = MesagxiloBabilejo


# Форма участников чатов
class MesagxiloPartoprenantoFormo(forms.ModelForm):

    sciigoj = forms.ModelMultipleChoiceField(
        label=_('Тип способа уведомления'),
        queryset=InformilojSciigoTipo.objects.filter(forigo=False)
    )
    filter_horizontal = ('sciigoj', )

        # widget=forms.SelectMultiple,
        # widget=forms.CheckboxSelectMultiple,

    class Meta:
        model = MesagxiloPartoprenanto
        fields = [field.name for field in MesagxiloPartoprenanto._meta.fields if field.name not in ('krea_dato', 'uuid')]\
                 + ['sciigoj',]


# Участники чатов
@admin.register(MesagxiloPartoprenanto)
class MesagxiloPartoprenantoAdmin(admin.ModelAdmin):
    form = MesagxiloPartoprenantoFormo
    list_display = ('uuid',)
    filter_horizontal = ('sciigoj', )

    class Meta:
        model = MesagxiloPartoprenanto


# форма сообщения чатов
class MesagxiloMesagxoFormo(forms.ModelForm):
    teksto = forms.CharField(widget=LingvoInputWidget(), label=_('Teksto'), required=True)

    class Meta:
        model = MesagxiloMesagxo
        fields = [field.name for field in MesagxiloMesagxo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_teksto(self):
        out = self.cleaned_data['teksto']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Сообщения чатов
@admin.register(MesagxiloMesagxo)
class MesagxiloMesagxoAdmin(admin.ModelAdmin, TekstoMixin):
    form = MesagxiloMesagxoFormo
    # list_display = ('uuid')
    list_display = ('uuid', 'teksto_teksto')
    exclude = ('uuid',)

    class Meta:
        model = MesagxiloMesagxo


# Форма вложения к сообщениям чатов
class MesagxiloInvestojFormo(forms.ModelForm):

    class Meta:
        model = MesagxiloInvestoj
        fields = [field.name for field in MesagxiloInvestoj._meta.fields if field.name not in ('krea_dato', 'uuid')]


# вложения к сообщениям чатов
@admin.register(MesagxiloInvestoj)
class MesagxiloInvestojAdmin(admin.ModelAdmin, TekstoMixin):
    form = MesagxiloInvestojFormo
    # list_display = ('id')
    # exclude = ('id',)

    class Meta:
        model = MesagxiloInvestoj
